-- AlwaysSuccess
--
---@type behavior_ret
local bret = import('bt/bt_plugin/behavior3/behavior_ret')

local M = {
    name = 'RecordFailNode',
    type = 'Decorator',
    desc = '记录返回失败的节点',
    args = {
        { "condCount", "int?", "可失败次数(默认两次)" }
    },
    doc = [[
        + 只能有一个子节点,多个仅执行第一个
        + 记录子节点失败次数
        + 成功时会清零
    ]]
}

function M.run(node, env)
    local owner = env.owner
    local children = node.children[1]
    local condCount = node.args.condCount
    --local childrenName = children.name
    local keyName = children.name
    local failNode = owner.failNodes[keyName]
    if not owner.failNodes[keyName] then
        owner.failNodes[keyName] = {}
        failNode = owner.failNodes[keyName]
        failNode.name = children.name
        failNode.info = children.info
        failNode.count = 0
        failNode.condCount = 2
        if condCount then
            failNode.condCount = condCount
        end
    end

    local yield, last_ret = node:resume(env)
    if yield then
        if last_ret == bret.RUNNING then
            return last_ret
        elseif last_ret == bret.FAIL then
            failNode.count = failNode.count + 1
        elseif last_ret == bret.SUCCESS then
            failNode.count = 0
        end
        return last_ret
    end

    local r = children:run(env)
    if r == bret.RUNNING then
        return node:yield(env)
    elseif r == bret.FAIL then
        failNode.count = failNode.count + 1
    elseif r == bret.SUCCESS then
        failNode.count = 0
    end
    return r
end

return M
